package com.example.subscriber.recive;

import com.example.subscriber.config.SendMessagesConfig;
import com.example.utils.ValidateCodeUtils;
import com.example.utils.redis.RedisUtil;
import com.rabbitmq.client.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.io.IOException;

/**
 * @project: kaoshi
 * @description:
 * @author: cjq
 * @create: 2022-11-06 21:33
 **/
@Component
public class SendMessageRecive {
    @Autowired
    JavaMailSender mailSender;
    @Autowired
    RedisUtil redisUtil;
    @Value("${spring.mail.username}")
    private String from;
    private static final Logger log = LoggerFactory.getLogger(SendMessageRecive.class);

    @RabbitListener(queues = SendMessagesConfig.CJQ_SEND_MESSAGE_QUEUE_NAME)
    public void revice(Message message, Channel channel){
        try {
            String email = new String(message.getBody());
            SimpleMailMessage mailMessage = new SimpleMailMessage();
            //主题
            mailMessage.setSubject("验证码邮件");
            //生成随机数
            String code = ValidateCodeUtils.generateValidateCode(6).toString();
            if (StringUtils.isEmpty(redisUtil.get("code"))){
                redisUtil.set("code",code);
            }
            //内容
            mailMessage.setText("您收到的验证码是："+code);
            System.out.println(code);
            //发给谁
            mailMessage.setTo(email);
            //自己的邮箱
            mailMessage.setFrom(from);
            try {
                //发送
                mailSender.send(mailMessage);
            }catch (MailException e){
                e.printStackTrace();

            }
            log.info("我收到的消息是：{}", new String(message.getBody()));
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            e.printStackTrace();
            try {
                channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, false);
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
        }
    }

}
